package com.springboot.template.thread.synchronizedDemo;


import java.util.concurrent.locks.ReentrantLock;

class Seat2 implements Runnable {
    private int position = 100;
    
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (position > 0) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("从"+Thread.currentThread().getName()+"得到座位，座位号为：" + position);
                    --position;
                }else {
                    break;
                }
            }finally {
                lock.unlock();
            }
        }
    }

}

public class TestLock {
    public static void main(String[] args) {
        Seat2 seat2 = new Seat2();

        Thread t = new Thread(seat2);
        Thread t1 = new Thread(seat2);
        Thread t2 = new Thread(seat2);

        t.setName("渠道1");
        t1.setName("渠道2");
        t2.setName("渠道3");

        t.start();
        t1.start();
        t2.start();
    }
}
